/*
 * ------------------------------------------------------------------
 * 权限拦截中间件
 * ------------------------------------------------------------------
 * 检测请求的用户是否具备执行权限 , 此中间件对应拦截没有接口权限的用户
 * ------------------------------------------------------------------
 * @关于我：
 * QQ:2815473064
 * wechat:13531609457
 * ------------------------------------------------------------------
 */
const Redis = require("../../sql/redis");
module.exports = async (req, res, next) => {
  try {
    // 当前请求是否不拦截
    let ifSkip = req.$ifSkip;
    // 中间件开关
    let status = false;
    if (!status || ifSkip) {
      next();
    } else {
      let ProjectName = "TardeAdmin";
      let user = req.$user;
      // 取出用户角色
      let userInfoRedisPath = `${ProjectName}:user:Info:${user}`;
      let RedisUserInfo = await Redis.get(userInfoRedisPath);
      let userInfo = JSON.parse(RedisUserInfo);
      let userRoles = userInfo.roles;
      console.log("当前用户：", user);
      console.log("当前用户角色", userRoles);
      // 当前接口地址
      let CurrentPath = req.$pathname;

      let PathAuthList = await Redis.lRange(
        `${ProjectName}:Auth:Path:list`,
        0,
        -1
      );
      let { id: CurrentPathId, state: CurrentPathState } = PathAuthList.map(
        (i) => JSON.parse(i)
      ).find((i) => i.path == CurrentPath);

      // 获取角色中所拥有的接口权限
      let RolePathList = await Redis.lRange(
        `${ProjectName}:Auth:RolePath:list`,
        0,
        -1
      );

      // 角色是否拥有该接口权限
      let RoleIfPathAuth = RolePathList.map((i) => JSON.parse(i)).some(
        (i) => i.path_id == CurrentPathId
      );

      console.log("CurrentPath", CurrentPath);
      console.log("CurrentPathId", CurrentPathId);
      console.log("RolePathList", RolePathList);
      console.log("RoleIfPathAuth", RoleIfPathAuth);

      if (!RoleIfPathAuth) {
        throw { code: 500, msg: "您没有该接口的访问权限" };
      } else {
        next();
      }
    }
  } catch (error) {
    console.log(error);
    throw error;
  }
};
